//
//  KZPronounceMakeTestVC_version2.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/26.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZPronounceMakeTestVC_version2.h"

// api
#import "KZPronounceNetApi.h"

// view
#import "KZPronounceTestView.h"   // 做题
#import "KZTimerView.h"
#import "KZAlertView.h"
#import "KZAllOverView.h"

@interface KZPronounceMakeTestVC_version2 ()

@property (nonatomic, strong) KZPronounceTestView *testView;
@property (nonatomic, strong) KZTimerView *timeView;
@end

@implementation KZPronounceMakeTestVC_version2

- (void)dealloc {
    NSLog(@"vc销毁了");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNaviUI];
    [self setupUI];
    
    // 计时器从0开始
    _timeView.time = 0;
}


#pragma mark - 创建视图
- (void)setupNaviUI {
    
    self.title = @"标准发音强化训练";
    [self addLeftBackBarButtonItem];
    
    _timeView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    __weak typeof(self) wself = self;
    _timeView.clickBlock = ^(BOOL isPause){
        if (isPause) {
            [wself.testView pauseSource];
            [wself rest];
        }
    };
    [self addCustomItemviews:@[_timeView] position:ByNavigationItemPositionModeRight];
    
}

- (void)setupUI {
    
    // 创建测试
    _testView = [KZPronounceTestView new];
    _testView.model = _soundmarkList[_index];
    [self.view insertSubview:_testView atIndex:0];
    [_testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.mas_equalTo(H(10));
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    __weak typeof(self) wself = self;
    _testView.nextBlock = ^ {
        [wself next];
    };
    _testView.successStayBlock = ^{
        __strong typeof(self) sself = wself;
        [sself saveCurrentPronounce];
        sself->_index ++;
    };
    _testView.failureStayBlock = ^{
        __strong typeof(self) sself = wself;
        [sself saveCurrentPronounce];
        sself->_index ++;
    };
}



#pragma mark - Net
// 做完了一遍
- (void)getStandarPronouncationInfo {
    
    // 销毁资源
    [_testView freeSource];
    [_timeView stop];
    
    [MBProgressHUD showLoadind:@"一轮训练已完成，正在查询待复习音标，请稍候..."];
    
    KZPronounceNetApi *api = [KZPronounceNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getStandarPronouncationInfo:^ (NSArray *list) {
        
        [MBProgressHUD hideHud];
        
        if (list.count == 0) {
            KZAllOverView *overView = [KZAllOverView new];
            [overView show];
            overView.okBlock = ^{
                [self dismissViewControllerAnimated:true completion:nil];
            };
        } else {
            // 音标列表
            _soundmarkList = list;
            // 弹框
            [self trainEnd];
        }
        
        
    } failuer:^(NSString *error) {
        
        [MBProgressHUD showFailureWithText:error];
    }];
}

// 保存当前音标
- (void)saveCurrentPronounce {
    
    KZPronounceNetApi *api = [KZPronounceNetApi new];
    NSMutableArray *temp = [NSMutableArray new];
    NSDictionary *modelDic = [_soundmarkList[_index] yy_modelToJSONObject];
    [temp addObject:modelDic];
    
    api.requestParam = @{
                         @"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,
                         @"ModelStandardPronunciationTrainDetailList": [temp copy]
                         };
    NSLog(@"kzkz: %@", api.requestParam.yy_modelToJSONString);
    [api saveStandarPronouncationInfo:^ {
        
    } failuer:^(NSString *error) {
        
    }];
}

#pragma mark - 事件
// 休息
- (void)rest {
    
    // 弹框提示
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:@"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n\t\t\t-----蓝小鸽"];
    if (_testView.isPauseAtRecording) {
//        subtitle = [[NSMutableAttributedString alloc] initWithString:@"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n\t\t\t-----蓝小鸽\n\n您在录音中暂停作答，恢复作答时将重新录音!!请准备!"];
//        [subtitle addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:[subtitle.string rangeOfString:@"您在录音中暂停作答，恢复作答时将重新录音!!请准备!"]];
         subtitle = [[NSMutableAttributedString alloc] initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦"];
    }
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        
        [_testView beginSource];
        [_timeView resume];
        
    } destroyAtClickIndex:@[@0]];
}
// 返回
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    // 点击返回按钮，先暂停当前训练
    [_testView pauseSource];
    [_timeView pause];
    
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:@"你确定要退出\n标准发音强化训练吗？"];
    if (_testView.isPauseAtRecording) {
//        subtitle = [[NSMutableAttributedString alloc] initWithString:@"你确定要退出\n标准发音强化训练吗？\n\n您在录音中暂停作答，恢复作答时将重新录音!!请准备!"];
//        [subtitle addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:[subtitle.string rangeOfString:@"您在录音中暂停作答，恢复作答时将重新录音!!请准备!"]];
         subtitle = [[NSMutableAttributedString alloc] initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦"];
    }
    
    // 弹框提示
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@0, @1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
        [buttons.lastObject setTitle:@"继续训练" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        // 点击退出
        if (index == 0) {
            // 销毁资源
            [_testView freeSource];
            [_timeView stop];
            [self dismissViewControllerAnimated:true completion:nil];
        }
        // 点击继续
        else {
            // 继续训练
            [_testView beginSource];
            [_timeView resume];
        }
        
    } destroyAtClickIndex:@[@0, @1]];
}

// 下一个音标
- (void)next {
    
    // 下一题
    if (_index < _soundmarkList.count) {

        // 创建视图
        KZPronounceTestView *testView = [KZPronounceTestView new];
        testView.model = _soundmarkList[_index];
        [self.view insertSubview:testView atIndex:0];
        [testView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(@0);
            make.top.mas_equalTo(H(10));
            if (@available(ios 11.0,*)) {
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.bottom.equalTo(@0);
            }
        }];
        __weak typeof(self) wself = self;
        testView.nextBlock = ^ {
            [wself next];
        };
        testView.successStayBlock = ^{
            __strong typeof(self) sself = wself;
            [sself saveCurrentPronounce];
            sself->_index ++;
        };
        testView.failureStayBlock = ^{
            __strong typeof(self) sself = wself;
            [sself saveCurrentPronounce];
            sself->_index ++;
        };
        
        [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            _testView.transform = CGAffineTransformMakeTranslation(-_testView.width, 0);
        } completion:^(BOOL finished) {
            [_testView freeSource];
            [_testView removeFromSuperview];
            
            _testView = testView;
        }];
    } else {
        // 请求新的列表
        [self getStandarPronouncationInfo];
    }
}
// 训练完成
- (void)trainEnd {
    
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:@"本轮音标训练已完成，是否进行下一轮训练！"];
    
    // 弹框提示
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@0, @1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
        [buttons.lastObject setTitle:@"继续训练" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        // 点击退出
        if (index == 0) {
            [self dismissViewControllerAnimated:true completion:nil];
        }
        // 点击继续
        else {
            [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            
            // 计时器从0开始
            _timeView.time = 0;
            _index = 0;
            
            
            [self next];
        }
        
    } destroyAtClickIndex:@[@0, @1]];
    
}


@end
